home *** CD-ROM | disk | FTP | other *** search
/ C/C++ Users Group Library 1996 July / C-C++ Users Group Library July 1996.iso / listings / v_12_02 / allison / commas.c < prev    next >
Encoding:
C/C++ Source or Header  |  1993-11-30  |  1.5 KB  |  67 lines

  1. LISTING 11 - Uses prepend and preprintf to format numbers with comma
  2. separators
  3. /* commas.c:    Converts a number into a string with commas */
  4.  
  5. #include <stdio.h>
  6.  
  7. #define BASE 10
  8. #define GROUP 3
  9.  
  10. /* Need space to hold the digits of an unsigned long,
  11.  * intervening commas and a null byte. It depends on
  12.  * BASE and GROUP above (but logarithmically, not
  13.  * as a constant, so we must define it manually here)
  14.  */
  15. #define MAXTEXT 14      /* For BASE = 10 */
  16.  
  17. int prepend(char *, unsigned, char *);
  18. int preprintf(char *, unsigned, char *, ...);
  19.  
  20. char *commas(unsigned long amount)
  21. {
  22.     short offset = MAXTEXT-1,   /* where the string "starts" */
  23.           place;                /* the power of BASE for current digit */
  24.     static char text[MAXTEXT];
  25.  
  26.     text[offset] = '\0';
  27.  
  28.     /* Push digits right-to-left with commas */
  29.     for (place = 0; amount > 0; ++place)
  30.     {
  31.         if (place % GROUP == 0 && place > 0)
  32.             offset = prepend(text,offset,",");
  33.         offset = preprintf(text,offset,"%x",amount % BASE);
  34.         amount /= BASE;
  35.     }
  36.  
  37.     return (offset >= 0) ? text + offset : NULL;
  38. }
  39.  
  40. main()
  41. {
  42.     puts(commas(1));
  43.     puts(commas(12));
  44.     puts(commas(123));
  45.     puts(commas(1234));
  46.     puts(commas(12345));
  47.     puts(commas(123456));
  48.     puts(commas(1234567));
  49.     puts(commas(12345678));
  50.     puts(commas(123456789));
  51.     puts(commas(1234567890));
  52.     return 0;
  53. }
  54.  
  55. /* Output:
  56. 1
  57. 12
  58. 123
  59. 1,234
  60. 12,345
  61. 123,456
  62. 1,234,567
  63. 12,345,678
  64. 123,456,789
  65. 1,234,567,890
  66. */
  67.